package com.bl.nio.server.handler;

import com.bl.nio.common.constant.Const;
import com.bl.nio.common.entity.SocketClient;
import com.bl.nio.common.handler.IEventHandler;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 作者 : blownsow
 * @version 版本: 1.0
 * @date 创建时间 : 2019/12/7 10:47
 * @describe 类描述:
 */
public class AcceptHandler implements Runnable {
    private ExecutorService executorService = Executors.newCachedThreadPool();

    private ServerSocket serverSocket;

    private IEventHandler eventHandler;

    public AcceptHandler(ServerSocket serverSocket, IEventHandler eventHandler) {
        this.serverSocket = serverSocket;
        this.eventHandler = eventHandler;
    }

    @Override
    public void run() {
        while (!serverSocket.isClosed()){
            try {
                Socket socket = serverSocket.accept();
                SocketClient socketClient = new SocketClient();
                socketClient.setSocket(socket);
                socketClient.setClientId(UUID.randomUUID().toString());
                //超时时间（未收到消息自动断开）
                socketClient.setTimeout(Const.SERVER_HEARTBEAT_TIMEOUT_TIMES);
                executorService.execute(new ClientHandler(socketClient,eventHandler));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
